package cn.echisan.springbootjwtdemo.config;

import cn.echisan.springbootjwtdemo.exception.JWTAccessDeniedHandler;
import cn.echisan.springbootjwtdemo.exception.JWTAuthenticationEntryPoint;
import cn.echisan.springbootjwtdemo.filter.JWTAuthenticationFilter;
import cn.echisan.springbootjwtdemo.filter.JWTAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * @EnableWebSecurity
 *
 * @Import({WebSecurityConfiguration.class, SpringWebMvcImportSelector.class})
 * 1: 加载了WebSecurityConfiguration配置类, 配置安全认证策略。
 * 激活了WebSecurityConfiguration配置类,在这个配置类中, 注入了一个非常重要的bean,
 * bean的name为: springSecurityFilterChain，这是Spring Secuity的核心过滤器, 这是请求的认证入口。
 * 2: 加载了AuthenticationConfiguration, 配置了认证信息。
 *@EnableGlobalAuthentication
 * 激活了AuthenticationConfiguration配置类, 这个类是来配置认证相关的核心类, 这个类的主要作用是,
 * 向spring容器中注入AuthenticationManagerBuilder, AuthenticationManagerBuilder其实是使用了建造者模式,
 * 他能建造AuthenticationManager, 这个类前面提过,是身份认证的入口。
 *
 * 当我们想要开启spring方法级安全时，只需要在任何 @Configuration实例上使用 @EnableGlobalMethodSecurity 注解就能达到此目的。
 * @EnableGlobalMethodSecurity(prePostEnabled = true)
 *
 * prePostEnabled = true 会解锁 @PreAuthorize 和 @PostAuthorize 两个注解。
 * 从名字就可以看出@PreAuthorize 注解会在方法执行前进行验证，而 @PostAuthorize 注解会在方法执行后进行验证。
 */
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsServiceImpl")
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                //ADMIN用户 才能执行 Delete 操作
                .antMatchers(HttpMethod.DELETE, "/tasks/**").hasRole("ADMIN")
                // 测试用资源，需要验证了的用户才能访问
                .antMatchers("/tasks/**").authenticated()
                // 其他都放行了
                .anyRequest().permitAll()
                .and()
                //认证过滤器
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                //授权过滤器
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                // 不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //检查 token 是否携带，或者是否有效
                .exceptionHandling().authenticationEntryPoint(new JWTAuthenticationEntryPoint())
                //检查是否访问权限
                .accessDeniedHandler(new JWTAccessDeniedHandler());      //添加无权限时的处理
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}
